package org.jeecg.modules.excel.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.checkerframework.checker.units.qual.A;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.engine.entity.Frame;
import org.jeecg.modules.engine.service.IFrameService;
import org.jeecg.modules.excel.entity.FrameY;
import org.jeecg.modules.excel.entity.MatClassY;
import org.jeecg.modules.excel.entity.MatY;
import org.jeecg.modules.materialclass.entity.MaterialClass;
import org.jeecg.modules.materialclass.service.IMaterialClassService;
import org.jeecg.modules.materiel.entity.Materiel;
import org.jeecg.modules.materiel.service.IMaterielService;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.entity.SysUserDepart;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysUserDepartService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.workgroup.entity.GroupUser;
import org.jeecg.modules.workgroup.entity.WorkGroup;
import org.jeecg.modules.workgroup.service.IWorkGroupService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/excel/import")
public class ExcelImportController {

    @Autowired
    private IMaterialClassService materialClassService;

    @Autowired
    private IMaterielService materielService;

    @Autowired
    private IFrameService frameService;

    @Autowired
    private ISysDepartService departService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysUserDepartService userDepartService;

    @Autowired
    private IWorkGroupService workGroupService;

    @RequestMapping("/mat_class")
    @Transactional
    public Result<?> matClass(HttpServletRequest request) throws IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            HSSFWorkbook hssfWorkbook = new HSSFWorkbook(file.getInputStream());
            HSSFSheet sheet = hssfWorkbook.getSheetAt(0);
            try {
                List<MatClassY> list = new ArrayList<>();
                for (int i = 1;i<=sheet.getLastRowNum();i++){
                    MatClassY matClassY = new MatClassY();
                    matClassY.setCode(sheet.getRow(i).getCell(1).getStringCellValue());
                    matClassY.setName(sheet.getRow(i).getCell(2).getStringCellValue());
                    list.add(matClassY);
                }
                List<MatClassY> parent = list.stream().filter(p -> p.getCode().length() == 2).collect(Collectors.toList());
                List<MatClassY> secondparent = list.stream().filter(p -> p.getCode().length() == 4).collect(Collectors.toList());
                List<MatClassY> threeparent = list.stream().filter(p -> p.getCode().length() == 6).collect(Collectors.toList());
                List<MatClassY> fourparent = list.stream().filter(p -> p.getCode().length() == 8).collect(Collectors.toList());
                Map<String,String> map = new HashMap<>();
                parent.forEach(p -> {
                    MaterialClass materialClass = new MaterialClass();
                    materialClass.setMaterialClassCode(p.getCode());
                    materialClass.setMaterialClass(p.getName());
                    materialClass.setParentId("0");
                    if (list.stream().filter(a ->a.getCode().startsWith(p.getCode())).count()>1){
                        materialClass.setHasChild("1");
                    }
                    materialClassService.save(materialClass);
                    map.put(p.getCode(),materialClass.getId());
                });
                secondparent.forEach(p -> {
                    MaterialClass materialClass = new MaterialClass();
                    materialClass.setMaterialClassCode(p.getCode());
                    materialClass.setMaterialClass(p.getName());
                    materialClass.setParentId(map.get(p.getCode().substring(0,2)));
                    if (list.stream().filter(a ->a.getCode().startsWith(p.getCode())).count()>1){
                        materialClass.setHasChild("1");
                    }
                    materialClassService.save(materialClass);
                    map.put(p.getCode(),materialClass.getId());
                });
                threeparent.forEach(p -> {
                    MaterialClass materialClass = new MaterialClass();
                    materialClass.setMaterialClassCode(p.getCode());
                    materialClass.setMaterialClass(p.getName());
                    materialClass.setParentId(map.get(p.getCode().substring(0,4)));
                    if (list.stream().filter(a ->a.getCode().startsWith(p.getCode())).count()>1){
                        materialClass.setHasChild("1");
                    }
                    materialClassService.save(materialClass);
                    map.put(p.getCode(),materialClass.getId());
                });
                fourparent.forEach(p ->{
                    MaterialClass materialClass = new MaterialClass();
                    materialClass.setMaterialClassCode(p.getCode());
                    materialClass.setMaterialClass(p.getName());
                    materialClass.setParentId(map.get(p.getCode().substring(0,6)));
                    materialClassService.save(materialClass);
                    map.put(p.getCode(),materialClass.getId());
                });
                return Result.ok("文件导入成功！数据行数：" + list.size());
            } catch (Exception e) {
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }

    @RequestMapping("/mat")
//    @Transactional
    public Result<?> test(HttpServletRequest request) throws IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            HSSFWorkbook hssfWorkbook = new HSSFWorkbook(file.getInputStream());
            HSSFSheet sheet = hssfWorkbook.getSheetAt(0);
            List<MaterialClass> materialClassList = materialClassService.list();
            Map<String,String> classMap = new HashMap<>();
            materialClassList.forEach(p -> {
                classMap.put(p.getMaterialClassCode(),p.getId());
            });
            List<Materiel> materielList = new ArrayList<>();
            try {
                for (int i = 1;i<sheet.getLastRowNum();i++){
                    Materiel materiel =new Materiel();
                    if (sheet.getRow(i).getCell(1) != null){
                        materiel.setMatCode(sheet.getRow(i).getCell(1).getStringCellValue());
                    }
                    if (sheet.getRow(i).getCell(2) != null){
                        materiel.setMatName(sheet.getRow(i).getCell(2).getStringCellValue());
                    }
                    if (sheet.getRow(i).getCell(3)!=null){
                        materiel.setMatStandard(sheet.getRow(i).getCell(3).getStringCellValue());
                    }
                    if (sheet.getRow(i).getCell(4) != null){
                        materiel.setMatClassId(classMap.get(sheet.getRow(i).getCell(4).getStringCellValue()));
                    }
                    if (sheet.getRow(i).getCell(13) != null){
                        materiel.setMatUnit(sheet.getRow(i).getCell(13).getStringCellValue());
                    }
                    materielList.add(materiel);
                }
                materielService.saveBatch(materielList);
            } catch (Exception e) {
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok();
    }

    @RequestMapping("/addFrame/{mainId}")
    public Result<?> addFrame(HttpServletRequest request,@PathVariable("mainId") String mainId) throws IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        List<Frame> frameList = new ArrayList<>();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            HSSFWorkbook hssfWorkbook = new HSSFWorkbook(file.getInputStream());
            HSSFSheet sheet = hssfWorkbook.getSheetAt(0);
            for (int i = 4;i<sheet.getLastRowNum()-1;i++){
                Frame frame = new Frame();
                frame.setEngineeringId(mainId);
                frame.setStatus(1);
                frame.setDoneCount(0);
                frame.setSteelSpecification(sheet.getRow(i).getCell(0).getStringCellValue());
                frame.setStandard(sheet.getRow(i).getCell(1).getStringCellValue());
                frame.setQualit(sheet.getRow(i).getCell(2).getStringCellValue());
                frame.setFigureNumber(sheet.getRow(i).getCell(3).getStringCellValue());
                sheet.getRow(i).getCell(5).setCellType(Cell.CELL_TYPE_STRING);
                sheet.getRow(i).getCell(6).setCellType(Cell.CELL_TYPE_STRING);
                sheet.getRow(i).getCell(7).setCellType(Cell.CELL_TYPE_STRING);
                sheet.getRow(i).getCell(8).setCellType(Cell.CELL_TYPE_STRING);
                String stringCellValue = sheet.getRow(i).getCell(5).getStringCellValue();
                frame.setCount(Integer.parseInt(stringCellValue));
                frame.setArea(Double.parseDouble(sheet.getRow(i).getCell(6).getStringCellValue()));
                frame.setSingleWeight(Double.parseDouble(sheet.getRow(i).getCell(7).getStringCellValue()));
                frame.setTotalWeight(Double.parseDouble(sheet.getRow(i).getCell(8).getStringCellValue()));
                frame.setRemark(sheet.getRow(i).getCell(9).getStringCellValue());
                frameList.add(frame);
            }

        }
        frameService.saveBatch(frameList);
        return Result.ok();
    }

    @RequestMapping("/addDept")
    @Transactional
    public Result<?> addDept(HttpServletRequest request) throws IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        Map<String,String> map = new HashMap<>();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            HSSFWorkbook hssfWorkbook = new HSSFWorkbook(file.getInputStream());
            HSSFSheet sheet = hssfWorkbook.getSheetAt(0);
            List<SysDepart> departList = new ArrayList<>();
            for (int i = 1;i<sheet.getLastRowNum();i++){
                String orgCode = sheet.getRow(i).getCell(1).getStringCellValue();
                if (orgCode.length()==2){
                    SysDepart depart = new SysDepart();
                    depart.setOrgCode(orgCode);
                    depart.setDepartName(sheet.getRow(i).getCell(2).getStringCellValue());
                    depart.setStatus("1");
                    depart.setDelFlag("0");
                    depart.setOrgType("2");
                    String deptName = sheet.getRow(i).getCell(2).getStringCellValue();
                    if (deptName.substring(deptName.length()-1).equals("部")){
                        depart.setOrgCategory("1");
                    }else if (deptName.substring(deptName.length()-1).equals("包") || deptName.substring(deptName.length()-1).equals("）")){
                        depart.setOrgCategory("3");
                    }else if (deptName.substring(deptName.length()-1).equals("组")){
                        depart.setOrgCategory("4");
                    }else {
                        depart.setOrgCategory("2");
                    }
                    departList.add(depart);
                }
            }
            departService.saveBatch(departList);

            for (int i = 2;i<sheet.getLastRowNum();i++){
                String orgCode = sheet.getRow(i).getCell(1).getStringCellValue();
                if (orgCode.length()==4){
                    SysDepart depart = new SysDepart();
                    depart.setOrgCode(orgCode);
                    depart.setDepartName(sheet.getRow(i).getCell(2).getStringCellValue());
                    SysDepart sysDepart = departList.stream().filter(p -> {
                        String substring = orgCode.substring(0, 2);
                        return p.getOrgCode().equals(substring);
                    }).findFirst().get();
                    depart.setParentId(sysDepart.getId());
                    depart.setStatus("1");
                    depart.setDelFlag("0");
                    depart.setOrgType("2");
                    String deptName = sheet.getRow(i).getCell(2).getStringCellValue();
                    if (deptName.substring(deptName.length()-1).equals("部")){
                        depart.setOrgCategory("1");
                    }else if (deptName.substring(deptName.length()-1).equals("包") || deptName.substring(deptName.length()-1).equals("）")){
                        depart.setOrgCategory("3");
                    }else if (deptName.substring(deptName.length()-1).equals("组")){
                        depart.setOrgCategory("4");
                    }else {
                        depart.setOrgCategory("2");
                    }
                    departService.save(depart);
                }
            }
        }
        return Result.ok();
    }

    @RequestMapping("/addUser")
    @Transactional
    public Result<?> addUser(HttpServletRequest request) throws IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        Map<String, String> map = new HashMap<>();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            HSSFWorkbook hssfWorkbook = new HSSFWorkbook(file.getInputStream());
            HSSFSheet sheet = hssfWorkbook.getSheetAt(0);
            List<SysDepart> departList = departService.list();
            Map<String,String> idMap = new HashMap<>();
            departList.forEach(p ->{
                map.put(p.getDepartName(),p.getOrgCode());
                idMap.put(p.getOrgCode(),p.getId());
            });
            List<SysUser> userList = new ArrayList<>();
            for (int i = 1; i < sheet.getLastRowNum(); i++) {
                SysUser user = new SysUser();
                user.setUsername(sheet.getRow(i).getCell(1).getStringCellValue());
                user.setRealname(sheet.getRow(i).getCell(2).getStringCellValue());
                String deptName = sheet.getRow(i).getCell(3).getStringCellValue();
                user.setOrgCode(map.get(deptName));
                user.setPassword("123456");
                user.setStatus(1);
                user.setDelFlag(0);
                user.setActivitiSync(1);
                String sex = sheet.getRow(i).getCell(6).getStringCellValue();
                if (sex.equals("男")){
                    user.setSex(1);
                }else if (sex.equals("女")){
                    user.setSex(2);
                }else {
                    user.setSex(0);
                }
                userList.add(user);
            }
            userService.saveBatch(userList);
            List<SysUserDepart> userDeparts = new ArrayList<>();
            userList.forEach(p -> {
                SysUserDepart userDepart = new SysUserDepart(p.getId(),idMap.get(p.getOrgCode()));
                userDeparts.add(userDepart);
                userService.changePassword(p);
            });
            userDepartService.saveBatch(userDeparts);
        }
        return Result.ok();
    }

    @RequestMapping("/addWorkGroup")
    @Transactional
    public Result<?> addWorkGroup(){
        List<SysDepart> group = departService.list(new LambdaQueryWrapper<SysDepart>().like(SysDepart::getDepartName, "组"));
        int count = workGroupService.count();
        group.forEach(p->{
            WorkGroup workGroup = new WorkGroup();
            workGroup.setWorkGroupCode("G"+String.format("%3d",count+1));
            workGroup.setWorkGroupName(p.getDepartName());
            workGroup.setCreateTime(new Date());
            workGroup.setCreateBy("admin");
            workGroupService.save(workGroup);
            List<SysUserDepart> sysUserDeparts = userDepartService.list(new LambdaQueryWrapper<SysUserDepart>().eq(SysUserDepart::getDepId, p.getId()));
            for (SysUserDepart sysUserDepart : sysUserDeparts) {
                GroupUser groupUser = new GroupUser();
                groupUser.setUserId(sysUserDepart.getUserId());
                groupUser.setWorkGroupId(workGroup.getId());
            }
        });
        return Result.ok();
    }


}
